import 'dart:ui';

import 'package:common_utils/common_utils.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart' as web;
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/common/PrimayButton.dart';
import 'package:magic_car/common/nodata.dart';
import 'package:magic_car/common/playvideo.dart';
import 'package:magic_car/common/showbottomsheet.dart';
import 'package:magic_car/user/anserdetail.dart';
import 'package:magic_car/user/checkstudyinfo.dart';
import 'package:magic_car/user/taskdetail.dart';
import 'package:magic_car/user/taskincome.dart';
import 'package:magic_car/user/taskorder.dart';
import 'package:magic_car/user/testvideo.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player/video_player.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

// import 'package:flutter_file_preview/flutter_file_preview.dart';

class UpvideosPage extends StatefulWidget {
  final String tid;

  UpvideosPage(this.tid);
  @override
  _MyHomePageState createState() => new _MyHomePageState(this.tid);
}

class _MyHomePageState extends State<UpvideosPage> {
  final String tid;
  _MyHomePageState(this.tid);
  VideoPlayerController _playcontroller;
  List formList;
  ScrollController _controller = new ScrollController();
  String _retrieveDataError;
  int page = 1;
  bool end = false;
  String keyword = "";
  var imgsLeng = 0;
  String current_pdf_url;
  File videos;
  bool _saving = false;
  bool hasvideo = false;
  bool uploadingvideo = false;
  String oid = "";
  var explainStr = "";
  var orderinfo;
  var taskinfo;
  bool iscommit = false;
  final ImagePicker _picker = ImagePicker();
  initState() {
    super.initState();
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        print('滑动到了最底部');
        // loadData();
      }
    });

    formList = [];
    loadData();
  }

  Future<void> _playVideo(PickedFile file) async {
    if (file != null && mounted) {
      // await _disposeVideoController();
      if (kIsWeb) {
        // _controller = VideoPlayerController.network(file.path);
        // // In web, most browsers won't honor a programmatic call to .play
        // // if the video has a sound track (and is not muted).
        // // Mute the video so it auto-plays in web!
        // // This is not needed if the call to .play is the result of user
        // // interaction (clicking on a "play" button, for example).
        // await _controller.setVolume(0.0);
      } else {
        _playcontroller = VideoPlayerController.file(File(file.path));
        await _playcontroller.setVolume(1.0);
      }
      await _playcontroller.initialize();
      await _playcontroller.setLooping(true);
      await _playcontroller.play();
      setState(() {});
    }
  }

  Widget _previewVideo() {
    final Text retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_controller == null) {
      return const Text(
        'You have not yet picked a video',
        textAlign: TextAlign.center,
      );
    }
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: AspectRatioVideo(_playcontroller),
    );
  }

  Text _getRetrieveErrorWidget() {
    if (_retrieveDataError != null) {
      final Text result = Text(_retrieveDataError);
      _retrieveDataError = null;
      return result;
    }
    return null;
  }

  //加载数据
  loadData() async {
    // if(keyword!=""){
    //   print(keyword);
    // if(end)return;
    // }
    // if (end) return;
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = pref.getString('uid');
    map["page"] = page.toString();
    map["keyword"] = keyword;
    map['tid'] = this.tid;
    print(map);

    HttpHelper.post(HttpHelper.API_TaskVideos, (data) async {
      if (data != null) {
        print(data);
        setState(() {
          explainStr = data["info"]['explain'];
          taskinfo = data["info"]['taskinfo'];
        });
        if (data["info"]['usertask']['finishtime'].toString() != "0") {
          //已完成
          setState(() {
            iscommit = true;
          });
          if (data["info"]['usertask']['order_id'].toString() != "0") {
            setState(() {
              oid = data["info"]['usertask']['order_id'].toString();
              orderinfo = data["info"]['usertask']['orderinfo'];
            });
          }
        }

        if (data["info"]['video'].length == 0) {
          Toast.show('暂无更多数据', context);
        } else {
          if (data["code"].toString() == "1") {
            if (data["info"]['video'].length < 10) {
              setState(() {
                end = true;
              });
            }
            if (page > 1) {
              List add = data["info"]['video'];
              formList.addAll(add);
              setState(() {
                formList = formList;
              });
            } else {
              setState(() {
                formList = data["info"]['video'];
                page = page + 1;
              });
            }
          }
        }
      }
    }, params: map);
  }

  Widget buildImgs(item) {
    List<Widget> tiles = [];

    Widget content;

    List items = item["image_url"];
    print(items.length.toString());

    for (var i = 0; i < items.length; i++) {
      //List temp1 = items[i] as List;
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(5, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
              // print('点击查看图片');
              // Navigator.of(context).push(
              //   NinePicture(items, i),
              // );
            },
            child: Image.network(items[i], width: 100, height: 100)),
      ));
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    if (formList.length > 0) {
      for (var item in formList) {
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(15, 15, 15, 0),
            child: Container(
              decoration: new BoxDecoration(
                color: Colors.white,
              ),
              child: new GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  // if (item["video_status"].toString() == "2") {
                  //   //已经上传了视频
                  //   Navigator.of(context)
                  //       .push(new MaterialPageRoute(builder: (_) {
                  //     return new PlayVideoPage(item['video_url']);
                  //   }));
                  // } else {
                  //   if (item["video_status"].toString() == "1") {
                  //     //
                  //     Toast.show('视频正在上传', context);
                  //   } else {
                  //     //没有上传视频
                  //     showModalBottomSheet(
                  //         context: context,
                  //         builder: (BuildContext context) {
                  //           return Primaybottomsheet(
                  //             text: '选择视频来源',
                  //             confirmPressed: () async {
                  //               Navigator.pop(context);

                  //               uploadVideo(1, item['taskid']);
                  //             },
                  //             confirmtext: '录视频',
                  //             canceltext: '从相册选取',
                  //             cancelPressed: () {
                  //               Navigator.pop(context);

                  //               uploadVideo(2, item['taskid']);
                  //             },
                  //           );
                  //         });
                  //   }
                  // }
                },
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Container(
                    //     width: 80,
                    //     child: new Column(children: <Widget>[
                    //       Padding(
                    //           padding: new EdgeInsets.fromLTRB(10, 10, 0, 10),
                    //           child:
                    //       // Image.network(item['taskimage'])
                    //       Image.asset('resource/images/user/videos.png',
                    //           width: 70, height: 90),
                    //       //Text('视频已上传',style: TextStyle(fontSize: 11,)),
                    // )])),
                    Container(
                        child: new Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                          Padding(
                              padding: new EdgeInsets.fromLTRB(10, 10, 20, 5),
                              child:RichText(text: TextSpan(
                                children: [
                                  TextSpan(text:item["title"],style: TextStyle(color: Colors.black)),
                                  item['is_must'].toString()=="1"?TextSpan(text:'*',style: TextStyle(color: Colors.red,fontSize: 20)):TextSpan(text:'')
                                ]
                              ))
                              // child: Text(item["title"])
                              ),
                          Padding(
                              padding: new EdgeInsets.fromLTRB(10, 10, 20, 5),
                              child: Text(
                                '视频限制：' + item["max"].toString() + '个',
                                style: TextStyle(fontSize: 13),
                              )),

                          Padding(
                              padding: new EdgeInsets.fromLTRB(10, 10, 20, 5),
                              child: videosview(item)),
                          // Padding(
                          //     padding: new EdgeInsets.fromLTRB(10, 0, 20, 5),
                          //     child: Text(
                          //       '领取时间：' + item["picktime"],
                          //       style: TextStyle(
                          //           fontSize: 13,
                          //           color: Color.fromRGBO(153, 153, 153, 1)),
                          //     )),
                          Padding(
                              padding: new EdgeInsets.fromLTRB(10, 10, 20, 10),
                              child: new Row(children: [
                                // PrimayButton(
                                //     onPressed: () {
                                //       popcontent(item['descrble']);
                                //     },
                                //     text: '视频要求',
                                //     textcolor: Colors.white,
                                //     colors: Colors.blue,
                                //     width: 100,
                                //     height: 30,
                                //     bordercolor: Colors.blue,
                                //     borderwidth: 1),
                                Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(0, 0, 0, 0),
                                    child: iscommit == true
                                        ? Container(height: 0)
                                        : PrimayButton(
                                            onPressed: () {
                                              showModalBottomSheet(
                                                  context: context,
                                                  builder:
                                                      (BuildContext context) {
                                                    return Padding(
                                                        padding: new EdgeInsets
                                                                .fromLTRB(
                                                            0, 0, 0, 0),
                                                        child: Container(
                                                          height: 80,
                                                          child: new Column(
                                                              children: <
                                                                  Widget>[
                                                                new Container(
                                                                    decoration:
                                                                        new BoxDecoration(
                                                                            border:
                                                                                Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
                                                                    height: 40,
                                                                    child: new GestureDetector(
                                                                        behavior: HitTestBehavior.opaque,
                                                                        onTap: () {
                                                                          Navigator.pop(
                                                                              context);
                                                                          if (item['videos'].length <
                                                                              int.parse(item['max'])) {
                                                                            //可以上传
                                                                            uploadVideo(2,
                                                                                item);
                                                                          } else {
                                                                            Toast.show('已经超过视频限制',
                                                                                context);
                                                                          }
                                                                        },
                                                                        child: Center(child: Text('相册', style: TextStyle(fontSize: 16, color: Colors.red))))),
                                                                new Container(
                                                                    height: 40,
                                                                    child: new GestureDetector(
                                                                        behavior: HitTestBehavior.opaque,
                                                                        onTap: () {
                                                                          Navigator.pop(
                                                                              context);
                                                                          uploadVideo(
                                                                              1,
                                                                              item);
                                                                        },
                                                                        child: Center(child: Text('拍视频', style: TextStyle(fontSize: 16))))),
                                                              ]),
                                                        ));
                                                  });
                                            },
                                            text: '选取视频',
                                            textcolor: Colors.white,
                                            colors: Colors.blue,
                                            width: 100,
                                            height: 30,
                                            bordercolor: Colors.blue,
                                            borderwidth: 1))
                              ])),
                          // Padding(
                          //     padding: new EdgeInsets.fromLTRB(10, 0, 20, 5),
                          //     child: Text(
                          //       '查看视频要求>>',
                          //       style: TextStyle(
                          //           fontSize: 13,
                          //           color: Color.fromRGBO(153, 153, 153, 1)),
                          //     )),
                          // item["shenhe"] == ""
                          //     ? new Container(height: 0)
                          //     : Padding(
                          //         padding:
                          //             new EdgeInsets.fromLTRB(10, 0, 20, 5),
                          //         child: Text(
                          //           item['shenhe'],
                          //           style: TextStyle(
                          //               fontSize: 13,
                          //               color: Color.fromRGBO(223, 99, 83, 1)),
                          //         )),
                        ])),
                  ],
                ),
                // child: new Row(

                //     children: <Widget>[
                //       Column(
                //         mainAxisAlignment: MainAxisAlignment.start,
                //         crossAxisAlignment: CrossAxisAlignment.start,
                //         children: <Widget>[
                //           Padding(
                //             padding: new EdgeInsets.fromLTRB(20, 15, 20, 10),
                //             child: Column(
                //               children: <Widget>[Text(item["tasktitle"])],
                //             ),
                //           ),
                //           Padding(
                //             padding: new EdgeInsets.fromLTRB(20, 0, 20, 10),
                //             child: Row(
                //               children: <Widget>[
                //                 Expanded(
                //                     flex: 1,
                //                     child: Text(
                //                       '领取时间：' + item["picktime"],
                //                       style: TextStyle(
                //                           color: Color.fromRGBO(
                //                               153, 153, 153, 1),
                //                           fontSize: 13),
                //                     )),
                //               ],
                //             ),
                //           ),
                //         ],
                //       )
                //     ])
              ),
            )));
      }
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //编辑视频
  editvideo(item, videoindex) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: item['videos'][videoindex]['isup'] == "0" ? 80 : 40,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height:
                          item['videos'][videoindex]['isup'] == "0" ? 40 : 0,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                            uploadvideos(item, videoindex);
                          },
                          child: Center(
                              child: Text('确认上传',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                            List temp = item['videos'];
                            if (temp[videoindex]['isup'] != "0") {
                              deleteRemotevideo(temp[videoindex]['videoid']);
                            }
                            temp.removeAt(videoindex);
                            setState(() {
                              formList = formList;
                            });
                          },
                          child: Center(
                              child:
                                  Text('删除', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  //删除服务器视频
  deleteRemotevideo(id) async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    // if (key != "0") {
    //   map["key"] = key;
    // }
    map['id'] = id.toString();

    HttpHelper.post(HttpHelper.API_DeleteVideos, (data) async {
      if (data != null) {
        Toast.show(data['msg'], context);
        if (data["code"].toString() == "1") {}
      }
    }, params: map);
  }

  //视频视图
  Widget videosview(item) {
    List<Widget> tiles = [];
    Widget content;

    for (var i = 0; i < item['videos'].length; i++) {
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(5, 0, 0, 10),
        child: GestureDetector(
            onLongPress: () {
              print('识别长按手势');
              if (iscommit == false) {
                editvideo(item, i);
              }
              // if (item['videos'][i]['isup'] == "0") {
              //   editvideo(item, i);
              // }
            },
            onTap: () {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                print('视频地址：'+item['videos'][i]['local']);
                return new PlayVideoPage(item['videos'][i]['local'], false);
              }));
            },
            child: Column(children: [
              Image.asset('resource/images/user/videos.png',
                  width: 100, height: 100),
              item['videos'][i]['isup'] == "0"
                  ? Padding(
                      padding: new EdgeInsets.fromLTRB(0, 5, 0, 5),
                      child: Container(
                        width: 100,
                        child: Center(
                            child: Text('长按视频进行上传',
                                style: TextStyle(fontSize: 11))),
                      ))
                  : new Container(
                      height: 0,
                      width: 0,
                    ),
              Container(
                  width: 100,
                  child:
                   LinearProgressIndicator(
                    value: double.parse(item['videos'][i]['progress']),
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.red),
                    backgroundColor: Colors.blue,
                  )),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 5, 0, 5),
                  child: Container(
                      width: 100,
                      child: Center(
                          child: Text(item['videos'][i]['progresspercent'])))),
            ])),
      ));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget showVideoType() {
    return Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
        child: Container(
          height: 80,
          child: new Column(children: <Widget>[
            new Container(
                decoration: new BoxDecoration(
                    border: Border(
                        bottom:
                            BorderSide(width: 1, color: Color(0xffe5e5e5)))),
                height: 40,
                child: new GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      uploadVideo(2, 1);
                    },
                    child: Center(
                        child: Text('相册',
                            style:
                                TextStyle(fontSize: 16, color: Colors.red))))),
            new Container(
                height: 40,
                child: new GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      uploadVideo(1, 1);
                    },
                    // onTap: () {
                    //   Navigator.pop(context);
                    // },
                    child: Center(
                        child: Text('拍视频', style: TextStyle(fontSize: 16))))),
          ]),
        ));
  }

  popcontent(contents) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new AlertDialog(
          title: new Text('视频要求'),
          content: new SingleChildScrollView(
            child: new ListBody(
              children: <Widget>[
                web.HtmlWidget(contents)
              // web.WebView(contents);
                // webView(contents)
                // Html(data: contents)
                ],
            ),
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  uploadVideo(type, item) async {
//  File result = await FilePicker.getFile(type: FileType.video);
//     if (result != null) {
//      // File file = File(result.files.single.path);
//     } else {
//       // User canceled the picker
//     }
    // File video = await ImagePicker.pickVideo(source: ImageSource.gallery);
    PickedFile videofile;
    File result;

    if (type == 1) {
      videofile = await _picker.getVideo(source: ImageSource.camera);
      result = File(videofile.path);
    } else {
      result = await FilePicker.getFile(type: FileType.video);

      // videofile = await _picker.getVideo(
      //     source: ImageSource.gallery);
      // videofile = await ImagePicker.pickVideo(source: ImageSource.gallery);
    }

    if (result == null) return;
    // String thumbnailPath = await VideoThumbnail.thumbnailFile(
    //     video: result.path,
    //     imageFormat: ImageFormat.PNG,
    //     maxWidth: 128,
    //     quality: 25);
    // print(thumbnailPath);
    List temparr = item["videos"];
    temparr.add({
      'local': result.path,
      'progress': '0',
      'progresspercent': '0%',
      'isup': '0'
    });
    setState(() {
      formList = formList;
    });
    //  Navigator.of(context)
    //                       .push(new MaterialPageRoute(builder: (_) {
    //                     return new PlayVideoPage(result.path,false);
    //                   }));

    // if (type != 1) {
    //   if (await result.length() > 200 * 1024) {
    //     print(result.length().toString());
    //     Toast.show('上传视频不得大于200M', context);
    //     return;
    //   }
    // }

    //  File tempFile  = File.fromUri(result.uri);
    //  tempFile.rename(tempFile.path+'.mp4');
    // File tempfile1 = File

    //  File files = File(videofile.path);
    // File files = video;
    //  setState(() {
    //    hasvideo = true;
    //  });

    // await _playVideo(videofile);
    // 先获取上传tokn
    // Map<String, String> map = new Map();
    // SharedPreferences pref = await SharedPreferences.getInstance();
    // map["id"] = pref.getString('uid');
    // HttpHelper.post(HttpHelper.API_QiniuToken, (data) async {
    //   if (data != null) {
    //     if (data["code"].toString() == "1") {
    //       //获取成功
    //       // updatetask("0", id);
    //       // PickedFile _files = videofile;
    //       Map<String, String> maps = new Map();
    //       SharedPreferences prefs = await SharedPreferences.getInstance();
    //       maps["id"] = prefs.getString('uid');
    //       maps["token"] = data['info']['token'];
    //       maps["key"] = data['info']['key'];

    //       maps["isgallery"] = type == 1 ? "0" : "1";

    //       HttpHelper.upLoadvideo(result, (data) {
    //         print(data);
    //         if (data.containsKey('code')) {
    //           Toast.show(data['msg'], context);
    //         } else {
    //           // updatetask(data['key'], id);
    //         }
    //       }, (int send, int total) {
    //         print('上传进度' + send.toString() + '文件大小：' + total.toString());

    //         var tempitem = temparr.last;
    //         tempitem['progress']=(send/total).toString();
    //         // tempitem['progresspercent']=((send/total)*100).toString()+'%';
    //         tempitem['progresspercent'] = NumUtil.getDoubleByValueStr(((send/total)*100).toString()).toStringAsFixed(2)+'%';
    //         setState(() {
    //           formList = formList;
    //         });

    //       }, params: maps);
    //     }
    //   }
    // }, params: map);

    // File _files = await FlutterNativeImage.compressImage(image.path);
  }

  //上传视频
  uploadvideos(item, index) async {
    if (uploadingvideo == true) {
      Toast.show('有视频正在上传，请等待上传完成后再操作', context);
      return;
    }
    File result;
    List temp = item['videos'];
    item['videos'][index]['isup'] = "1";
    print('上传的视频地址：'+temp[index]['local']);

    result = File(temp[index]['local']);
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = pref.getString('uid');
    HttpHelper.post(HttpHelper.API_QiniuToken, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          //获取成功
          // updatetask("0", id);
          // PickedFile _files = videofile;
          Map<String, String> maps = new Map();
          SharedPreferences prefs = await SharedPreferences.getInstance();
          maps["id"] = prefs.getString('uid');
          maps["token"] = data['info']['token'];
          maps["key"] = data['info']['key'];

          // maps["isgallery"] = type == 1 ? "0" : "1";

          HttpHelper.upLoadvideo(result, (data) {
            print(data);
            if (data.containsKey('code')) {
              Toast.show(data['msg'], context);
            } else {
              // updatetask(data['key'], id);

              var tempitem = temp[index];
              tempitem['isup'] = "2";

              updatevideo(data['key'], item, index); //上传完成更新视频信息

            }
          }, (int send, int total) {
            if (send == total) {
              setState(() {
                uploadingvideo = false;
              });
            } else {
              setState(() {
                uploadingvideo = true;
              });
            }
            print('上传进度' + send.toString() + '文件大小：' + total.toString());

            var tempitem = temp[index];
            tempitem['progress'] = (send / total).toString();
            // tempitem['progresspercent']=((send/total)*100).toString()+'%';
            tempitem['progresspercent'] =
                NumUtil.getDoubleByValueStr(((send / total) * 100).toString())
                        .toStringAsFixed(2) +
                    '%';
            setState(() {
              formList = formList;
            });
          }, params: maps);
        }
      }
    }, params: map);
  }

//更新任务
  updatetask() async {
    if (oid == "") {
      //
      Toast.show('请选择关联订单', context);
      return;
    }
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    // if (key != "0") {
    //   map["key"] = key;
    // }
    map['id'] = this.tid;
    map['oid'] = oid;
    HttpHelper.post(HttpHelper.API_UptTask, (data) async {
      if (data != null) {
        Toast.show(data['msg'], context);
        if (data["code"].toString() == "1") {
          // page = 1;
          // loadData(); //更新数据
          Navigator.pop(context);
        }
      }
    }, params: map);
  }

  //更新视频
  updatevideo(key, item, index) async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    map['vid'] = item["id"];
    map['local_ulr'] = item['videos'][index]['local'];
    map['remote_url'] = key;

    HttpHelper.post(HttpHelper.API_UptVideos, (data) async {
      if (data != null) {
        Toast.show(data['msg'], context);
        if (data["code"].toString() == "1") {
          // page = 1;
          // loadData(); //更新数据
        }
      }
    }, params: map);
  }

  Widget build(BuildContext context) {
    return
        // new MaterialApp(
        //     title: '结构件',
        //     home:
        new Scaffold(
            appBar: new AppBar(
              title: new Text(
                '上传视频',
                style: TextStyle(color: Colors.black),
              ),
              backgroundColor: Colors.white,
              elevation: 0,
              // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
            ),
            body: ModalProgressHUD(
                // color: Colors.blue,
                inAsyncCall: _saving,
                child: new Center(
                    child: hasvideo
                        ? _previewVideo()
                        : Container(
                            decoration: new BoxDecoration(
                              color: Color.fromRGBO(238, 238, 238, 1),
                            ),
                            child:
                                // new ListView(children: <Widget>[
                                Stack(
                              children: <Widget>[
                                Align(
                                  alignment: Alignment.topLeft,
                                  child: SizedBox(
                                      width: double.infinity,
                                      height: oid == "" ? 60 : 140,
                                      child: Padding(
                                          padding: new EdgeInsets.fromLTRB(
                                              15, 10, 15, 10),
                                          // padding: new EdgeInsets.all(10),
                                          child: GestureDetector(
                                              onTap: () {
                                                Navigator.of(context).push(
                                                    new MaterialPageRoute(
                                                        builder: (_) {
                                                  return new TaskUnionOrderPage();
                                                })).then((paramss) {
                                                  setState(() {
                                                    oid = paramss['id'];
                                                    orderinfo = paramss;
                                                  });
                                                });
                                              },
                                              child: Container(
                                                  child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .start,
                                                      children: <Widget>[
                                                    Expanded(
                                                      child: new Container(
                                                        height: oid == ""
                                                            ? 60
                                                            : 140,
                                                        child: Padding(
                                                            padding:
                                                                new EdgeInsets
                                                                        .fromLTRB(
                                                                    10,
                                                                    8,
                                                                    15,
                                                                    8),
                                                            child: oid == ""
                                                                ? new Text(
                                                                    '请选择关联订单')
                                                                : new Column(
                                                                    crossAxisAlignment:
                                                                        CrossAxisAlignment
                                                                            .start,
                                                                    mainAxisAlignment:
                                                                        MainAxisAlignment
                                                                            .start,
                                                                    children: [
                                                                        Padding(
                                                                            padding: new EdgeInsets.fromLTRB(
                                                                                0,
                                                                                0,
                                                                                0,
                                                                                3),
                                                                            child:
                                                                                Text('订单号：' + orderinfo['order_sn'])),
                                                                        Padding(
                                                                            padding: new EdgeInsets.fromLTRB(
                                                                                0,
                                                                                0,
                                                                                0,
                                                                                3),
                                                                            child:
                                                                                Text('检测完成时间：' + orderinfo['overtime'])),
                                                                        Padding(
                                                                            padding: new EdgeInsets.fromLTRB(
                                                                                0,
                                                                                0,
                                                                                0,
                                                                                3),
                                                                            child:
                                                                                new Text(
                                                                              '订单金额：' + '¥' + orderinfo['orderPrice'].toString(),
                                                                              style: TextStyle(),
                                                                            )),
                                                                        Padding(
                                                                            padding: new EdgeInsets.fromLTRB(
                                                                                0,
                                                                                0,
                                                                                0,
                                                                                3),
                                                                            child:
                                                                                Text('汽车品牌：' + orderinfo["brand_string"]["name"])),
                                                                      ])),
                                                        decoration:
                                                            new BoxDecoration(
//背景
                                                          color: Colors.white,
                                                          //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
                                                          // borderRadius:
                                                          //     BorderRadius.all(
                                                          //         Radius.circular(
                                                          //             25.0)),
                                                          //设置四周边框
                                                          border:
                                                              new Border.all(
                                                                  width: 1,
                                                                  color: Colors
                                                                      .white),
                                                        ),
                                                      ),
                                                    ),
                                                  ]))))),
                                ),
                                Align(
                                    alignment: Alignment.bottomCenter,
                                    child: Padding(
                                        padding: new EdgeInsets.fromLTRB(
                                            0, oid == "" ? 60 : 140, 0, 70),
                                        child: new RefreshIndicator(
                                          onRefresh: _onRefresh,
                                          child:
                                              formList.length == 0 && page == 1
                                                  ? Nodata()
                                                  : new ListView(
                                                      controller: _controller,
                                                      children: <Widget>[
                                                          buildcontent()
                                                        ]),
                                        ))),
                                //     Align(
                                // alignment: Alignment.bottomCenter,
                                // child: Padding(
                                //     padding: new EdgeInsets.fromLTRB(
                                //         15, 60, 15, 80),
                                //     child: PrimayButton(
                                //       containercolor:
                                //           Color.fromRGBO(238, 238, 238, 1),
                                //       text: '查看视频要求',
                                //       width: double.infinity - 30,
                                //       height: 40,
                                //       textcolor: Colors.white,
                                //       bordercolor:
                                //           Color.fromRGBO(223, 99, 83, 1),
                                //       colors:
                                //           Color.fromRGBO(223, 99, 83, 1),
                                //       borderwidth: 1,
                                //       onPressed: () {
                                //         updatetask();

                                //         // Navigator.of(context).push(
                                //         //     new MaterialPageRoute(
                                //         //         builder: (_) {
                                //         //   return new TaskAcountPage();
                                //         // }));
                                //       },
                                //     ))),
                                // Align(
                                //     alignment: Alignment.bottomLeft,
                                //     child: Padding(
                                //       padding: new EdgeInsets.fromLTRB(
                                //           15, 10, 15, 60),
                                //       child: new Text(
                                //           '注意：单个视频长度最长5分钟，此任务为一次性任务，若拍摄内容不符合要求，将得不到收益，且无法再次领取此任务',
                                //           style: TextStyle(
                                //               fontSize: 12, color: Colors.red)),
                                //     )),
                                Align(
                                    alignment: Alignment.bottomCenter,
                                    child: Padding(
                                        padding: new EdgeInsets.fromLTRB(
                                            15, 60, 15, 10),
                                        child: Row(children: [
                                          Expanded(
                                              flex: 1,
                                              child: Padding(
                                                  padding:
                                                      new EdgeInsets.fromLTRB(
                                                          0, 0, 15, 0),
                                                  child: PrimayButton(
                                                    containercolor:
                                                        Color.fromRGBO(
                                                            238, 238, 238, 1),
                                                    text: '视频要求',
                                                    width: 120,
                                                    height: 40,
                                                    textcolor: Colors.white,
                                                    bordercolor: Color.fromRGBO(
                                                        223, 99, 83, 1),
                                                    colors: Color.fromRGBO(
                                                        223, 99, 83, 1),
                                                    borderwidth: 1,
                                                    onPressed: () {
                                                      popcontent(explainStr);

                                                      // Navigator.of(context).push(
                                                      //     new MaterialPageRoute(
                                                      //         builder: (_) {
                                                      //   return new TaskAcountPage();
                                                      // }));
                                                    },
                                                  ))),
                                          Expanded(
                                              flex: 1,
                                              child: Padding(
                                                  padding:
                                                      new EdgeInsets.fromLTRB(
                                                          15, 0, 0, 0),
                                                  child: PrimayButton(
                                                    containercolor:
                                                        Color.fromRGBO(
                                                            238, 238, 238, 1),
                                                    text: '提交',
                                                    width: 120,
                                                    height: 40,
                                                    textcolor: Colors.white,
                                                    bordercolor:
                                                        iscommit == false
                                                            ? Color.fromRGBO(
                                                                223, 99, 83, 1)
                                                            : Colors.grey,
                                                    colors: iscommit == false
                                                        ? Color.fromRGBO(
                                                            223, 99, 83, 1)
                                                        : Colors.grey,
                                                    borderwidth: 1,
                                                    onPressed: () {
                                                      if (iscommit == false) {
                                                        showModalBottomSheet(
                                                            context: context,
                                                            builder:
                                                                (BuildContext
                                                                    context) {
                                                              return Primaybottomsheet(
                                                                text:
                                                                    '确定提交任务，提交后将不可更改？',
                                                                confirmtext:
                                                                    '确定',
                                                                confirmPressed:
                                                                    () {
                                                                  updatetask();
                                                                  Navigator.pop(
                                                                      context);
                                                                },
                                                                canceltext: '取消',
                                                                cancelPressed:
                                                                    () {
                                                                  Navigator.pop(
                                                                      context);
                                                                },
                                                              );
                                                            });
                                                      }

                                                      // Navigator.of(context).push(
                                                      //     new MaterialPageRoute(
                                                      //         builder: (_) {
                                                      //   return new TaskAcountPage();
                                                      // }));
                                                    },
                                                  ))),
                                        ])))
                              ],
                            )))
                //])))),
                ));
  }

  Future<Null> _onRefresh() async {
    await Future.delayed(Duration(seconds: 3), () {
      print('refresh');
      setState(() {
        page = 1;
      });
      loadData();
    });
  }
}

class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    // if (initialized != controller.value.initialized) {
    //   initialized = controller.value.initialized;
    //   setState(() {});
    // }
  }

  @override
  void initState() {
    super.initState();
    controller.addListener(_onVideoControllerUpdate);
  }

  @override
  void dispose() {
    controller.removeListener(_onVideoControllerUpdate);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller.value?.aspectRatio,
          child: VideoPlayer(controller),
        ),
      );
    } else {
      return Container();
    }
  }
}
